package com.lzk.es;

import com.lzk.utils.ESClientUtil;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;

import java.io.IOException;
import java.util.HashMap;

public class EsDemo {
    /**
     * 添加一个文档
     */
    @Test
    public void testAdd(){
        //获取es连接对象
        TransportClient client = ESClientUtil.getClient();
        //创建map存入数据
        HashMap<String,Object> map = new HashMap();
        map.put("id",1);
        map.put("name","张某某");
        map.put("age",12);
        map.put("sex",1);

        //创建索引+文档+文档id
        IndexRequestBuilder result = client.prepareIndex("pethome", "user", "1").setSource(map);
        System.out.println(result.get());
        // 关闭连接
        client.close();
    }

    /**
     * 查询一个文档
     */
    @Test
    public void testQuery(){
        //获取es连接对象
        TransportClient client = ESClientUtil.getClient();
        //获取指定文档
        GetResponse response = client.prepareGet("pethome", "user", "1").get();
        System.out.println(response);
        System.out.println(response.getSource());
        // 关闭连接
        client.close();
    }

    /**
     * 修改一个文档
     */
    @Test
    public void testUpdate(){
        //获取es连接对象
        TransportClient client = ESClientUtil.getClient();
        //准备修改的数据
        HashMap<String,Object> map = new HashMap();
        map.put("name","我在源码时代学习Java!我爱Java!");
        //修改指定文档
        UpdateResponse response = client.prepareUpdate("pethome", "user", "1").setDoc(map).get();
        System.out.println(response);
        // 关闭连接
        client.close();
    }

    /**
     * 修改一个文档
     */
    @Test
    public void testDel(){
        //获取es连接对象
        TransportClient client = ESClientUtil.getClient();
        //删除指定文档
        DeleteResponse response = client.prepareDelete("pethome", "user", "1").get();
        System.out.println(response);

        // 关闭连接
        client.close();
    }

    /**
     * 批量添加文档
     */
    @Test
    public void testBatch() throws Exception {
        //获取es连接对象
        TransportClient client = ESClientUtil.getClient();
        //创建批量操作对象
        BulkRequestBuilder bulk = client.prepareBulk();
        for (int i = 0; i < 100; i++) {
            IndexRequestBuilder builder = client.prepareIndex("pethome", "user", i + "").setSource(
                    XContentFactory.jsonBuilder()
                            .startObject()
                            .field("id", i - 1)
                            .field("name", "我在源码学习Java!" + i)
                            .field("age", i - 1)
                            .field("sex", i % 2)
                            .endObject()
            );
            BulkResponse response = bulk.add(builder).get();
            System.out.println(response.status());
        }
        // 关闭连接
        client.close();
    }

    /**
     * - 查询用户表
     * - name包含：我在源码
     * - age在1~12之间
     * - sex=1
     * - 每页大小2
     * - 从2页开始查
     * - 按照age倒序
     */
    @Test
    public void testDemo(){
        //获取es连接对象
        TransportClient client = ESClientUtil.getClient();
        //得到搜索对象
        SearchRequestBuilder pethome = client.prepareSearch("pethome");
        //指定搜索类型
        pethome.setTypes("user");
        // 指定Query搜索对象，当参数是接口时我们可以传递：接口的工具类、接口实现、匿名内部类，此处传递接口工具类
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //指定DSL查询，name包含我在源码
        boolQuery.must(QueryBuilders.matchQuery("name","我在源码"));
        //指定DSL过滤，age在1~12之间
        BoolQueryBuilder filter = boolQuery.filter(QueryBuilders.rangeQuery("age").gte(1).lte(12))
                .filter(QueryBuilders.termQuery("sex", 1));
        // 将搜索条件放入到搜索对象中
        pethome.setQuery(boolQuery);

        //设置分页size
        pethome.setSize(2);
        //设置第几页
        pethome.setFrom(4);
        //设置排序
        pethome.addSort("age", SortOrder.DESC);
        //获取查询结果
        SearchHits hits = pethome.get().getHits();
        System.out.println(hits.getTotalHits());

        for (SearchHit document : hits) {
            System.out.println(document.getSourceAsMap());
        }

        // 关闭连接
        client.close();
    }
}
